﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ECGWeb
{
    public partial class ECGSite : System.Web.UI.MasterPage
    {
        ECGService.ECGServiceClient serviceClient = new ECGService.ECGServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            this.btn_logout.Click += new EventHandler(btn_logout_Click);   
            if (Session["username"] == null || Session["permission"] == null)
            {
            }
            else
            {
                setPageAfterLogin((int)Session["permission"]);
            }
        }

        protected void btn_logout_Click(object sender, EventArgs e)
        {            
            Session.RemoveAll();
            Response.Redirect("~/HomePage.aspx");
        }

        protected void btn_login_Click(object sender, EventArgs e)
        {
            ECGService.User user = new ECGService.User();
            user = serviceClient.getUserByUsernamePassword(this.txt_id.Text, this.txt_pass.Text);
            if (user != null)
            {
                Session["username"] = user.username;
                Session["permission"] = user.permission;
                Session["realID"] = user.realID;
                switch (user.permission)
                {
                    case 1:
                        Response.Redirect("~/UserManagePage.aspx");
                        break;
                    case 2:
                        Response.Redirect("~/DoctorPage.aspx");
                        break;
                    case 3:
                        Response.Redirect("~/PatientPage.aspx");
                        break;
                }
            }
            else
            {
                showMessage("Wrong username or password! Please check again!");
            }
        }

        public void setPageAfterLogin(int permission)
        {
            tc_status.Controls.Clear();
            tc_status.Controls.Add(new LiteralControl("<i>Welcome " + Session["username"].ToString() + "</i>"));
            tc_login.Visible = false;
            tc_logout.Visible = true;

            switch (permission)
            {
                case 1:
                    tc_userManagementPage.Visible = true;
                    break;
                case 2:
                    tc_doctorPage.Visible = true;
                    break;
                case 3:
                    tc_patientpage.Visible = true;
                    break;
            }
        }

        public void showMessage(string text)
        {
            string strBuilder = "<script language='javascript'>alert('" + text + "')</script>";
            Response.Write(strBuilder);
        }
    }
}